#!/bin/bash
# End-to-End Test Script for KWDB Ingest System

set -e

PROJECT_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
BUILD_DIR="$PROJECT_ROOT/build"

echo "=== KWDB Ingest Test Suite ==="
echo "Project root: $PROJECT_ROOT"
echo ""

# Step 1: Setup environment
echo "[1/5] Setting up environment..."
source "$PROJECT_ROOT/deploy/scripts/setup_env.sh"

# Step 2: Check if psql is available
echo ""
echo "[2/5] Checking psql availability..."
if ! command -v psql &> /dev/null; then
    echo "ERROR: psql command not found. Please install PostgreSQL client."
    exit 1
fi
echo "✓ psql is available"

# Step 3: Create tables (if database is accessible)
echo ""
echo "[3/5] Creating test tables..."
if psql -h "$KWDB_HOST" -p "$KWDB_SQL_PORT" -U "$KWDB_USER" -d "$KWDB_DB" \
        -f "$PROJECT_ROOT/deploy/scripts/create_tables.sql" 2>&1; then
    echo "✓ Tables created successfully"
else
    echo "⚠  Warning: Could not create tables. Database may not be accessible."
    echo "   You can skip this step if tables already exist or test without database."
fi

# Step 4: Check if ingestd is built
echo ""
echo "[4/5] Checking if ingestd is built..."
if [ ! -f "$BUILD_DIR/server/ingestd/ingestd" ]; then
    echo "ERROR: ingestd not found at $BUILD_DIR/server/ingestd/ingestd"
    echo "Please run: cd build && cmake --build . --target ingestd"
    exit 1
fi
echo "✓ ingestd found"

# Step 5: Instructions
echo ""
echo "[5/5] Ready to test!"
echo ""
echo "=== Manual Test Instructions ==="
echo ""
echo "Terminal 1 - Start ingestd:"
echo "  cd $BUILD_DIR/server/ingestd"
echo "  ./ingestd"
echo ""
echo "Terminal 2 - Run write example:"
echo "  cd $BUILD_DIR/examples/cpp"
echo "  ./write_example"
echo ""
echo "Terminal 3 - Verify data:"
echo "  psql -h $KWDB_HOST -p $KWDB_SQL_PORT -U $KWDB_USER -d $KWDB_DB \\"
echo "    -c \"SELECT COUNT(*) FROM cpu_metrics;\""
echo ""
echo "=== Test Checklist ==="
echo "□ ingestd starts and shows: [ingestd] listen on 0.0.0.0:9090"
echo "□ write_example shows: ✓ Single point write succeeded"
echo "□ write_example shows: ✓ Batch write of X points succeeded"
echo "□ psql query returns row count > 0"
echo "□ ingestd logs show: [sql_writer] written=X points, elapsed=Yms"
echo ""
echo "=== Error Testing ==="
echo "Test 1: Stop ingestd and run write_example"
echo "  Expected: Transport error with gRPC connection failure"
echo ""
echo "Test 2: Send empty batch (use grpcurl if available)"
echo "  Expected: code!=0 with 'empty batch' message"
echo ""
echo "===============================Done================================"